<?php
/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: dzf_base_lmemory.php 4190 2014-09-26 04:22:30Z laoguozhang $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class dzf_base_lmemory extends dzf_base_class
{
	
	public $prefix = '';
	public $ttl = 180;//5分钟
	/**
	 * get
	 * 根据key获取记录
	 *
	 * @param  string|array $key 键值
	 * @param string $pre_cache_key key前缀
	 * @return string 对应value的值
	 */
	public function get($key, $pre_cache_key = null) {
		$ret = FALSE;
		if(function_exists('apc_fetch')) {
			$success = FALSE;
			$ret = apc_fetch($this->_key($key, $pre_cache_key), $success);
			if($success === false) {
				$ret = false;
			} else {
				if(is_array($key)) {
					if(count($key) !== count($ret)) {
						$ret = false;
					} else {
						$data = array();
						foreach($ret as $k => $v) {
							$data[$this->_trim_key($k, $pre_cache_key)] = $v;
						}
						$ret = $data;
					}
				}
			}
		}
		return $ret;
	}

	/**
	 * set
	 * 覆盖记录
	 *
	 * @param  string $key Key
	 * @param  array $data 数据
	 * @param string $pre_cache_key key前缀
	 * @param  integer $expire 有效期，0为永久
	 * @return boolean
	 */
	public function set($key, $data, $pre_cache_key = null, $expire = null) {
		$ret = FALSE;
		if(function_exists('apc_store')) {
			$key = (string)$this->_key($key, $pre_cache_key);
			//key 小于2位时直接返回false
			if(!isset($key[1])) {
				return false;
			}
			if($expire === null) {
				$expire = $this->ttl;
			}
			$ret = apc_store($key, $data, $expire);
		}
		return $ret;
	}

	/**
	 * rm
	 * 删除记录
	 *
	 * @param  string $table 表名
	 * @param  string|array $key Key
	 * @param string $pre_cache_key key前缀
	 * @return boolean
	 */
	public function rm($key, $pre_cache_key = null) {
		$ret = FALSE;
		if(function_exists('apc_delete')) {
			$ret = apc_delete($this->_key($key, $pre_cache_key));
		}
		return $ret;
	}

	/**
	 * 内部函数 追加键值前缀
	 * @param string|array $str
	 * @param string $pre_cache_key key前缀
	 * @return string|array 处理结果
	 */
	private function _key($str, $pre_cache_key=null) {
		if($pre_cache_key !== null) {
			$this->prefix = $pre_cache_key;
		}
		if(is_array($str)) {
			foreach($str as &$val) {
				$val = $this->prefix.$val;
			}
		} else {
			$str = $this->prefix.$str;
		}
		return $str;
	}

	/**
	 * 清除键值前缀
	 * @param string|array $str
	 * @param string $pre_cache_key key前缀
	 * @return string|array 处理结果
	 */
	private function _trim_key($str, $pre_cache_key = null) {
		if($pre_cache_key !== null) {
			$this->prefix = $pre_cache_key;
		}
		return substr($str, strlen($this->prefix));
	}
}